var menuDataSrc = null;
var parentTabSelect = null;
$(document).ready(function () {
    menuDataSrc = new kendo.data.HierarchicalDataSource({
        transport: {
            read: {
                url: "/TabManager/GetTabsTv",
                type: "POST",
                dataType: "json"
            }
        },
        schema: {
            model: {
                id: "Id",
                children: "ChildTabs",
                hasChildren: "HasChildren"
            }
        }
    });

    $("#Tabs-tree").kendoTreeView({
        dataSource: menuDataSrc,
        dragAndDrop: true,
        dataTextField: "TabName",
        select: onTreeSelect,
        drop: onTreeDrop
    });

    parentTabSelect = $("#ParentTabId").kendoComboBox({
        placeholder: "Select Parent TAb",
        dataTextField: "TabName",
        dataValueField: "Id",
        filter: "contains",
        autoBind: false,
        minLength: 3,
        dataSource: menuDataSrc
    }).data("kendoComboBox");

    if ($("#menusmpl").length > 0) {
        $("#menusmpl").kendoMenu({
            //dataSource: dataSrc,
            dataTextField: "TabName"
        });
    }

    $("#StartDate").kendoDatePicker();
    $("#EndDate").kendoDatePicker();
    $("#TabOrder").kendoNumericTextBox();
    $("#btnSaveTv").bind("click", SaveTreeChanges);

    $('#form0').submit(function (e) {
        return chkfrm();
    });
    $('#frmReset').click(function (e) {
        $('#form0')[0].reset();
        $('#hid').val('');
    });
});

function chkfrm() {
    var hasUrl = false, hasCntrllrAction = false, hasTabName = false, htsTabTitle = false;
    var fld = $('#TabName');
    if (fld.val() == '') {
        makered('#TabName');
        hasTabName = false;
    }
    else {
        remred('#TabName');
        hasTabName = true;
    }
    fld = $('#TabTitle');
    if (fld.val() == '') {
        // alert('Please enter your Name.');
        makered('#TabTitle');
        htsTabTitle = false;
    }
    else {
        remred('#TabTitle');
        htsTabTitle = true;
    }
    if ($('#PermanentRedirect').is('checked')) {
        if ($('#PermanentRedirectUrl').val() == '') {
            makered('#PermanentRedirectUrl');
        }
        else
            hasUrl = true;
    }
    else {
        remred('#PermanentRedirectUrl');
        hasUrl = true;
    }

    if ((($('#TabController').val() != '') && ($('#TabControllerAction').val() == '')) ||
            (($('#TabControllerAction').val() != '') && ($('#TabController').val() == ''))) {
        makered('#TabController');
        makered('#TabControllerAction');

        hasCntrllrAction = false;
    }
    else {
        hasCntrllrAction = true;
    }
        
    //if (!hasUrl && !hasCntrllrAction) {
    //    makered('#PermanentRedirectUrl');
    //    makered('#TabController');
    //    makered('#TabControllerAction');
    //}
    //else {
    //   remred('#PermanentRedirectUrl');
    //   remred('#TabController');
    //   remred('#TabControllerAction');
    //}
    return hasTabName && htsTabTitle && hasCntrllrAction;
}

function makered(v) {
    if ($(v).length > 0) { $(v).css('border-color', '#B70000'); }
}
function remred(v) {
    if ($(v).length > 0) { $(v).removeAttr('style'); }
}
function pgfrmSuccess() {
    $("#frmMailmessage").hide();
    $("#lblMessage").show();
}
function onFormSuccess(data, status, xhr) {
    menuDataSrc.read();
    $('#form0')[0].reset();
    $('#hid').val('');
    //update tab tree
    //alert(data);
}

function onFormFailure(xhr, status, error) {
    //alert("Whoops! That didn't go so well did it?");
}

function onTreeSelect(e) {
    var dataItem = this.dataItem(e.node);
    var uri = "/TabManager/GetTab/" + dataItem.Id;
    $.ajax({
        url: uri,
        type: "POST",
        dataType: "json",
        context: document.body
    }).success(function (data) {
        $.each(data, function (key, value) {
            var ele = $('#' + (key == 'Id' ? 'hid' : key));
            if ($(ele).length > 0) {
                if (key == "TabOrder") {
                    var ntxtBox = $("#TabOrder").data("kendoNumericTextBox");
                    if (ntxtBox != null) {
                        ntxtBox.value(value);
                    }
                }
                if ((key == 'Id' ? 'hid' : key) == 'ParentTabId' && parentTabSelect != null) {
                    parentTabSelect.value(value);
                }
                else if (ele[0].localName == 'input') {
                    if (($(ele)[0].type == 'text' || $(ele)[0].type == 'hidden')) {
                        ele.val(value);
                    }
                    else if ($(ele)[0].type == 'checkbox') {
                        ele.prop('checked', value);
                    }
                }
            }
        });
    }).error(function (err) {
        alert("an error occured during your request.")
    });
}

function onTreeDrop(e) {
    var srcItem = this.dataItem(e.sourceNode),
        tgtItem = this.dataItem(e.dropTarget);
    var uri = "/TabManager/SaveTab/" + srcItem.Id;
}

var selectedID;
var menuItems = new Array();
function SaveTreeChanges() {

    selectedID = '';

    var tv = $("#Tabs-tree").data("kendoTreeView");

    selectedID = getRecursiveMenuItems(tv.dataSource.view(), null);

    var data = {};
    data.str = selectedID;
    var menuString = { tabs: menuItems };
    $.ajax({
        type: 'POST',
        url: '/TabManager/UpdateTabs/',
        data: menuString,
        dataType: 'json',
        success: function (result) {
            tv.dataSource.read();
        },
        error: function (data, textStatus) {
            alert(textStatus);
        },
    });
}

function getRecursiveMenuItems(nodeview, parentId) {
    for (var i = 0; i < nodeview.length; i++) {
        var item = new TabTv();
        item.Id = parseInt(nodeview[i].id);
        item.TabName = nodeview[i].TabName;
        item.ParentTabId = parentId;
        menuItems.push(item);
        //nodeview[i].text; You can also access text here
        if (nodeview[i].hasChildren) {
            getRecursiveMenuItems(nodeview[i].children.view(), nodeview[i].id);
        }
    }

    return selectedID;
}

function getRecursiveNodeText(nodeview) {
    for (var i = 0; i < nodeview.length; i++) {
        selectedID += nodeview[i].id + ",";
        //nodeview[i].text; You can also access text here
        if (nodeview[i].hasChildren) {
            getRecursiveNodeText(nodeview[i].children.view());
        }
    }

    return selectedID;
}

function TabTv() {
    this.Id = 0;
    this.TabName = 0;
    this.ParentTabId = null;
    this.HasChildren = false;
}